import { Schema, SchemaOptions } from "mongoose";
import moment from "moment";
/**
 * 自动生成时间戳 [添加时间和更新时间]
 * @param schema
 * @param otions
 */
export default function timestamp(schema, option = {}) {
    let options = Object.assign({new : true}, option);
    schema.add({
        created_at: { type: Date, default: Date.now, get: v => moment(v).format('YYYY-MM-DD HH:mm')},
        updated_at: { type: Date, default: Date.now, get: v => moment(v).format('YYYY-MM-DD HH:mm') },
    });
    // 保存之前中间件， 设置更新时间
    schema.pre('save', function (next) {
        if (!this.created_at) {
            this.created_at = new Date();
        }
        this.updated_at = new Date();
        next();
    });

    // 文档更新中间件
    schema.pre('findOneAndUpdate', updateCreatedAt);
    schema.pre('findOneAndRemove', updateCreatedAt);
    schema.pre('updateOne', updateCreatedAt);
    schema.pre('update', updateCreatedAt);
    schema.pre('updateMany', updateCreatedAt);


    /**
     * 更新修改时间
     * @param next
     */

    function updateCreatedAt(next) {
        let document = this.getUpdate();
        document.updated_at = new Date();
        next();
    }
}